import time

import streamlit as st
import streamlit_authenticator as stauth
import yaml
from datetime import datetime, timedelta
from yaml.loader import SafeLoader
import traceback

def load_config():
    """加载 config.yaml 配置"""
    with open("config.yaml", "r", encoding="utf-8") as file:
        config = yaml.load(file, Loader=SafeLoader)
    return config

def save_config(config):
    """保存 config.yaml 配置"""
    with open("config.yaml", "w", encoding="utf-8") as file:
        yaml.dump(config, file, default_flow_style=False)

def init_authenticator():
    """初始化认证器对象"""
    config = load_config()
    authenticator = stauth.Authenticate(
        "config.yaml",
        config["cookie"]["name"],
        config["cookie"]["key"],
        config["cookie"]["expiry_days"]
    )
    return authenticator

def login_page(authenticator: stauth.Authenticate):
    """登录页面"""
    try:
        config = load_config()
        max_attempts = config["system_settings"]["max_login_attempts"]
        authenticator.login(max_login_attempts=max_attempts)
    except Exception as e:
        st.error(e)

def is_default_password(username, password):
    """检查是否为默认密码"""
    return stauth.Hasher.check_pw("abc123456", password)

def validate_username(username):
    """验证用户名格式（仅允许英文字母和数字）"""
    import re
    return bool(re.match(r'^[a-zA-Z0-9]+$', username))

def get_next_user_id(config):
    """获取下一个用户ID"""
    max_id = 0
    for _, user_data in config["credentials"]["usernames"].items():
        user_id = int(user_data.get("user_id", "00000"))
        max_id = max(max_id, user_id)
    return f"{max_id + 1:05d}"

def check_password_expiry(username):
    """检查密码是否过期"""
    config = load_config()
    user_data = config["credentials"]["usernames"].get(username, {})
    last_password_change = user_data.get("last_password_change")

    if not last_password_change:
        return True  # 如果没有修改日期记录，视为过期

    expiry_days = config["system_settings"]["password_expiry_days"]
    last_change = datetime.strptime(last_password_change, '%Y-%m-%d')
    expiry_date = last_change + timedelta(days=expiry_days)

    return datetime.now() > expiry_date

def update_password_change_date(username):
    """更新密码修改日期"""
    config = load_config()
    config["credentials"]["usernames"][username]["last_password_change"] = datetime.now().strftime('%Y-%m-%d')
    save_config(config)
